using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using ThomasTym.BoxGame.World;

namespace ThomasTym.BoxGame
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class BoxGame : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        GraphicsDevice device;

        Matrix viewMatrix;
        Matrix projectionMatrix;

        Vector3 cameraReference = Vector3.Backward;
        Vector3 cameraPosition = new Vector3(1.5f, 0.5f, 1.5f);
        Vector3 cameraTarget = Vector3.Zero;
        Vector3 cameraUp = Vector3.Up;
        float cameraYaw = 0.0f;
        Vector3 movement = Vector3.Zero;

        Map map;

        bool gameWon = false;

        DateTime lastSecond;

        SpriteFont font;

        Texture2D spiderTexture;

        bool test = true;

        public BoxGame()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 600;
            graphics.IsFullScreen = false;
            this.IsMouseVisible = true;
            graphics.SynchronizeWithVerticalRetrace = true;
            this.IsFixedTimeStep = false;
            graphics.ApplyChanges();
            Window.Title = "Tutorial2";

            this.Window.AllowUserResizing = true;
            this.Window.ClientSizeChanged += new EventHandler<EventArgs>(Window_ClientSizeChanged);              

            lastSecond = DateTime.Now; 
            
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            device = graphics.GraphicsDevice;
            spiderTexture = Content.Load<Texture2D>(@"Textures\m402Aa0");
            font = Content.Load<SpriteFont>("Spritefont1");

            viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, cameraUp);
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.01f, 500.0f);
            
            map = new Map(100, 1, 100);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here            
            ProcessKeyBoard(gameTime);                                        
            UpdateCamera(gameTime);             

            int fps = (int)(1000 / gameTime.ElapsedGameTime.TotalMilliseconds);
            if ((DateTime.Now.AddMilliseconds(-1000)) > lastSecond)
            {
                Window.Title = "FPS: " + fps.ToString() + "---" + cameraPosition.ToString();
                lastSecond = DateTime.Now;
            }

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

            DrawMap();

            DrawUI(gameTime);

            base.Draw(gameTime);
        }

        private void DrawMap()
        {
            

            map.DrawMap(GraphicsDevice, cameraPosition, basicEffect);
        }

        private void DrawUI(GameTime gameTime)
        {
            string output = ((int)gameTime.TotalGameTime.TotalSeconds).ToString();
            double distanceToExit = Math.Pow((Math.Pow((map.ExitX - cameraPosition.X + 0.5f), 2.0f) + Math.Pow((map.ExitZ - cameraPosition.Z + 0.5f), 2.0f)), 0.5f) - 0.5f;
            output += " Sekunden - " + Math.Floor(distanceToExit).ToString() + " Meter";

            if (distanceToExit < 1.0f)
            {
                gameWon = true;
            }

            spriteBatch.Begin();
            spriteBatch.DrawString(font, output, new Vector2(0f, 0f), Color.White);
            if (gameWon)
            {
                spriteBatch.DrawString(font, "GEWONNEN", new Vector2(0f, 20f), Color.Gold);
            }
            //spriteBatch.Draw(spiderTexture,new Rectangle(100, 100, 100,100), Color.White);
            spriteBatch.End();
        }

        private void UpdateCamera(GameTime gameTime)
        {
            float fps = (float)(1000 / gameTime.ElapsedGameTime.TotalMilliseconds);            

            Matrix rotationMatrix;
            Matrix.CreateRotationY(MathHelper.ToRadians(cameraYaw), out rotationMatrix);
            Vector3 transformedReference;

            if (movement != Vector3.Zero)
            {                   
                movement *= 0.05f * 60 / fps;                 

                Vector3.Transform(ref movement, ref rotationMatrix, out movement);
                Vector3 newPosition = cameraPosition + movement;
                if (map.IsWalkable(newPosition))
                {
                    cameraPosition = newPosition;
                }
                else
                {
                    Vector3 testPosition = new Vector3();
                    testPosition.X = newPosition.X;
                    testPosition.Y = cameraPosition.Y;
                    testPosition.Z = cameraPosition.Z;
                    if (map.IsWalkable(testPosition))
                    {
                        cameraPosition = testPosition;
                    }
                    else
                    {
                        testPosition.X = cameraPosition.X;
                        testPosition.Y = cameraPosition.Y;
                        testPosition.Z = newPosition.Z;
                        if (map.IsWalkable(testPosition))
                        {
                            cameraPosition = testPosition;
                        }
                    }
                }
            }

            Vector3.Transform(ref cameraReference, ref rotationMatrix, out transformedReference);
            Vector3.Add(ref cameraPosition, ref transformedReference, out cameraTarget);
            
            viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, cameraUp);
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.01f, 500.0f);     

        }

        void Window_ClientSizeChanged(object sender, EventArgs e)
        {
            viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, cameraUp);
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.01f, 500.0f);
        }

        void ProcessKeyBoard(GameTime gameTime)
        {
            float fps = (float)(1000 / gameTime.ElapsedGameTime.TotalMilliseconds);
            KeyboardState keyState = Keyboard.GetState();
            movement = Vector3.Zero;

            if (keyState.IsKeyDown(Keys.Left))
            {
                cameraYaw += 2.0f * 60 /fps;
            }

            if (keyState.IsKeyDown(Keys.Right))
            {
                cameraYaw -= 2.0f * 60 /fps;
            }

            if (cameraYaw > 360)
            {
                cameraYaw -= 360;
            }
            if (cameraYaw < 0)
            {
                cameraYaw += 360;
            }

            if (keyState.IsKeyDown(Keys.Up))
            {
                movement.Z++;
            }

            if (keyState.IsKeyDown(Keys.Down))
            {
                movement.Z--;
            }     
        }
    }
}
